<template>
  <el-dialog :visible="visible"
             :title="isUpdate ? '编辑' : '新增'"
             @close="visible = false">
    <el-form class="form">
      <el-form-item label="图片">
        <ImageUpload v-model="formData.pic"
                     @setImage="setImage" />
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="链接">
        <el-input v-model="formData.webUrl" />
      </el-form-item>
      <el-form-item label="sort">
        <el-input-number v-model="formData.sort" />
      </el-form-item>
    </el-form>
    <el-button @click="visible = false">取 消</el-button>
    <el-button type="primary"
               @click="confirm">确 定</el-button>
  </el-dialog>
</template>

<script>
import { getExhibitionById, saveExhibition, updateExhibition } from '@/api/bigdata/exhibition'
import ImageUpload from '@/components/Upload/ImageUpload'
export default {
  components: { ImageUpload },
  data () {
    return {
      visible: false,
      isUpdate: false,
      formData: {
        id: '',
        name: '',
        webUrl: '',
        description: '',
        pic: '',
        sort: 0
      },
    }
  },
  methods: {
    async init (id) {
      this.visible = true
      if (id != null) {
        this.isUpdate = true
        const data = await getExhibitionById(id)
        this.formData = data.data
      } else {
        this.isUpdate = false
        this.formData = {
          id: '',
          name: '',
          webUrl: '',
          description: '',
          pic: '',
          sort: 0
        }
      }
    },
    setImage (imageUrl) {
      this.formData.pic = imageUrl
    },
    confirm () {
      if (this.isUpdate) {
        this.handleConform(updateExhibition, this.formData)
      } else {
        this.handleConform(saveExhibition, this.formData)
      }
    },
    handleConform (operation) {
      operation(this.formData).then(response => {
        if (response.statusCode == 20000) {
          this.refresh()
          this.visible = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '发生错误，操作失败',
            type: 'warning'
          })
        }
      })
    },
    refresh () {
      this.$emit('refresh')
    }
  }
}
</script>

<style>
.form {
  margin-bottom: 20px;
}
</style>
